<?php

/*
 * This class is used for as Model for Job table 
 */
class Model_Uom extends Model_Base {

    protected $_name = 'tbl_uom';
    protected $_primaryKey = 'uom_id';

    /**
     * Fetch an individual entry
     *
     * @param  int|string $id
     * @return null|Zend_Db_Table_Row_Abstract
     */
    public function fetchEntryById($id) {
        $select = $this->select()
                ->from(array('uom' => 'tbl_uom'))
                ->where('uom_id = ?', $id);
        // see reasoning in fetchEntries() as to why we return only an array
        $data = $this->fetchRow($select);
        if (!empty($data)) {
            return $data->toArray();
        } else {
            return array();
        }
    }

    /**
     *  This function is used to get jobs
     * @return null|Zend_Db_Table_Row_Abstract
     */
    public function fetchUom($where = "", $limit = "", $offset = "0", $order = 'uom_id', $sort = 'ASC') {
        $select = $this->select()
                ->from(array('uom' => 'tbl_uom'));
        if ($where != '') {
            $select->where($where);
        }
        if ($limit != "") {
            $select->limit($limit, $offset);
        }
        $select->order($order . " " . $sort);
        $data = parent::fetchAll($select);
        if (!empty($data)) {
            return $data->toArray();
        } else {
            return array();
        }
    }
    
    
    /**
     * Fetch all units
     *
     * @return null|Array
     */
    public function fetchUomArray() {
        //Load UOM Model
        $uomModel = new Model_Uom();
        $uomArray = $uomModel->fetchAll();
        $finalArray['']= '-- Select Unit of measurement --';
        foreach($uomArray as $uom) {
            $finalArray[$uom['uom_key']] = $uom['uom_value'];
        }
        return $finalArray;    
    }
    
    /**
     *  This function is used to delete uoms
     * @return null|Zend_Db_Table_Row_Abstract
     */
    public function deleteUom($uom_id) {
        $uomData = $this->fetchEntryById($uom_id);
        $key = $uomData['uom_key'];
        
        
        //Load Product Model 
        $productModel = new Model_Product();
        $count = $productModel->getProductCount("prd_uom = '".$key."'");
        if ($count > 0 ) {
            echo "UOM_ALREADY_EXIST";
            exit;
        }
        //Load Job Model 
        $jobModel = new Model_Job();
        $jobCount = $jobModel->getJobCount("job_uom = '".$key."'");
        if ($jobCount > 0 ) {
            echo "UOM_ALREADY_EXIST";
            exit;
        }
        $this->delete('uom_id = ' . (int) $uom_id);
    }

}
